<template>
  <div class="mm-detail">
    <el-page-header @back="$router.push('/evaluate/monitoring')" content="监控管理详情"> </el-page-header>
    <div class="sec-detail-main">
      <!-- 监控详情tab页 -->
      <el-tabs type="border-card">
        <el-tab-pane label="监控详情">
          <!-- 基本信息 -->
          <secDescriptions
            :data="contentData"
            :colon="true"
            :labelStyle="{ width: '100px', 'text-align': 'right', 'line-height': '36px' }"
            :contentStyle="{ 'line-height': '36px' }"
            :column="3"
            :border="false"
            :keyData="baseKey"
            title="基础信息"
          >
          </secDescriptions>
          <div class="cls title">风险监控</div>
          <div class="btn-box" style="margin-bottom: 10px">
            <el-button type="primary" icon="el-icon-plus" @click="addMonitorIndex" v-if="codeSessionSign"
              >添加监控指标</el-button
            >
            <el-button type="primary" @click="monitorScan" v-if="codeSessionSign">发起监控扫描</el-button>
          </div>
          <sec-table
            :tableData="riskTable.rows"
            :tableCol="riskTable.cols"
            :loading="riskTable.loading"
            ref="riskTable"
          >
          </sec-table>

          <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page.sync="currentPage"
            background
            :page-sizes="pageSizes"
            :page-size="pageSize"
            :layout="layout"
            :total="totalSize"
          >
          </el-pagination>
        </el-tab-pane>
        <!-- 监控指标tab界面 -->
        <el-tab-pane label="监控指标">
          <secTable
            :optionData="evalResult.optionData"
            :tableData="evalResult.rows"
            :colType="evalResult.colType"
            :tableCol="evalResult.cols"
          ></secTable>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog title="新建异常监控指标" :visible.sync="indexDiaShow" width="50%">
      <myForm
        ref="monitoringIndex"
        :optionData="newIndex.optionData"
        :rules="newIndex.rules"
        :ruleForm="newIndex.ruleForm"
        :formData="newIndex.formData"
      ></myForm>
    </el-dialog>
    <el-dialog title="URL列表" :visible.sync="urlDiaShow" width="80%">
      <secTable :tableData="urlTable.rows" :tableCol="urlTable.cols"></secTable>
    </el-dialog>
    <el-dialog title="同步漏洞平台" :visible.sync="holeDiaShow" width="30%">
      <span>是否确认同步并生成审计报告？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="holeDiaShow = false">取 消</el-button>
        <el-button type="primary" @click="asyncHoleConfirm">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog title="误报" :visible.sync="errDiaShow" width="50%">
      <myForm ref="errReport" :rules="rules" :ruleForm="ruleForm" :formData="formData"></myForm>
    </el-dialog>
  </div>
</template>

<script>
import myForm from "components/formValidate/myForm";
import secTable from "components/table/comTable";
import secDescriptions from "components/descriptions/myDescriptions";
import { addWhiteMixin } from "common/js/mixin";
import {
  subsystemMonitorDetailApi,
  subsystemMonitorStartApi,
  subsystemMonitorGetItemsApi,
  assetSubsystemDetailApi,
  riskUrlsApi,
  listAllTinyRiskApi,
} from "api/evaluateApi";
import { riskListApi, riskSocApi, riskMisreportApi, riskHoleStatusApi, saveRiskItemApi } from "api/controlApi";

import { paginationMixin } from "common/js/mixin";
import { config } from "@/textConfig";
import { getCodeSession } from "@/utils";

export default {
  name: "monitoringDetail",
  props: {},
  mixins: [paginationMixin, addWhiteMixin],
  components: {
    myForm,
    secTable,
    secDescriptions,
  },
  data() {
    return {
      selectIndexRow: {}, //点击url列表时存储的行的数据
      codeSessionSign: true, //权限控制
      indexDiaShow: false,
      urlDiaShow: false, //url列表弹框
      errDiaShow: false, //误报弹框
      holeDiaShow: false, //同步漏洞平台弹框
      query: {},
      allRiskData: [], //风险名称全部数据
      selectRiskName: {},
      baseKey: [
        {
          label: "资产来源",
          prop: "source",
          formatter: (data) => {
            return this.utils.getDicLabel(100100, data.source);
          },
        },
        { label: "资产ID", prop: "id" },
        { label: "appID", prop: "assetCode" },
        { label: "域名", prop: "domain" },
        { label: "系统名称", prop: "assetName" },
        {
          label: "资产级别",
          prop: "importSystem",
          formatter: (data) => {
            return this.utils.getDicLabel(100400, data.importSystem);
          },
        },
        {
          label: "资产类型",
          prop: "assetType",
        },
        {
          label: "资产状态",
          prop: "status",
          formatter: (data) => {
            return this.utils.getDicLabel("100500", data.status);
          },
        },
        {
          label: "访问性",
          prop: "netDev",
          formatter: (data) => {
            return this.utils.getDicLabel(100200, data.netDev);
          },
        },
        { label: "权属负责人", prop: "leader" },
        { label: "权属部门", prop: "dept2" },
        { label: "BP", prop: "bp" },
        { label: "PM", prop: "pmName" },
        { label: "创建人", prop: "creator" },
        {
          label: "项目关注人",
          prop: "noticeUsers",
          formatter: () => {
            let { noticeUsers } = this.contentData;
            let con = "";
            if (noticeUsers && noticeUsers.length > 0) {
              noticeUsers.forEach((item) => {
                con += `${item.name} ；`;
              });
            }
            return con;
          },
        },
        { label: "录入时间", prop: "createTimeText" },
        { label: "监控任务ID", prop: "monitorId" },
        { label: "发起监控时间", prop: "createTimeText" },
        { label: "最近监控时间", prop: "lastestTimeText" },
        { label: "系统简介", prop: "extraData" },
        { label: "备注", prop: "remark1" },
      ],
      contentData: {},
      riskTable: {
        loading: false,
        cols: [
          { label: "风险名称", prop: "riskName", width: 250 },
          { label: "风险类型", prop: "holeType", width: 150 },
          { label: "风险描述", prop: "holeDetail" },
          { label: "修复建议", prop: "repairRecommend", width: 300, align: "left" },
          {
            label: "风险等级",
            prop: "level",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("level", cellValue);
            },
          },
          {
            label: "风险状态",
            prop: "status",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel(100700, cellValue);
            },
          },
          {
            label: "操作",
            prop: "operation",
            width: 220,
            children: [
              {
                label: "同步漏洞平台",
                hide: ({ row, column, $index }) => {
                  let arr = ["0"]; //风险状态码
                  return !arr.includes(row.status) || !getCodeSession();
                },
                click: ({ row, column, $index }) => {
                  this.holeDiaShow = true;
                  this.selectRisk = row;
                },
              },
              {
                label: "误报",
                hide: ({ row, column, $index }) => {
                  let arr = ["0"];
                  return !arr.includes(row.status) || !getCodeSession();
                },
                click: ({ row, column, $index }) => {
                  this.errDiaShow = true;
                  this.selectRisk = row;
                },
              },
              {
                label: "详情",
                click: ({ row, column, $index }) => {
                  this.$router.push({
                    path: "/control/risk/detail",
                    query: { riskId: row.id, assetId: row.assetId, code: row.code },
                  });
                },
              },
              {
                hide: ({ row, column, $index }) => {
                  let arr = ["1-4", "5"];
                  return !arr.includes(row.status) || !getCodeSession();
                },
                label: "同步工单状态",
                click: ({ row, column, $index }) => {
                  riskHoleStatusApi({ riskId: row.id, anquanId: row.anquanId }).then((res) => {
                    this.message.success({ message: res.msg });
                    this.getRiskList();
                  });
                },
              },
              {
                hide: ({ row, column, $index }) => {
                  let arr = ["0", "12"];
                  return arr.includes(row.status);
                },
                label: "工单详情",
                click: ({ row, column, $index }) => {
                  let domain = "http://anquan.didichuxing.com"; //测试的地址是http://anquan-test.didichuxing.com
                  window.open(`${domain}/project/portals/pages/hole-detail.html?id=${row.anquanId}`);
                },
              },
            ],
          },
        ],
        rows: [],
      },
      //新建指标弹出框数据
      newIndex: {
        optionData: {
          holeName: [],
          riskLevel: this.$store.state.dictionary.level,
        },
        ruleForm: {
          holeName: "",
          riskLevel: "",
          holeDetail: "",
        },
        rules: {
          holeName: [{ required: true, message: config.input, trigger: "blur" }],
          riskLevel: [{ required: true, message: config.input, trigger: "blur" }],
          holeDetail: [{ required: true, message: config.input, trigger: "blur" }],
        },
        formData: [
          {
            type: "select",
            label: "风险名称",
            filterable: true,
            prop: "holeName",
            optionProps: { label: "holeName", value: "id" },
            change: () => {
              this.getChangeRiskData();
            },
            clear: () => {
              this.newIndex.ruleForm.riskLevel = "";
              this.newIndex.ruleForm.holeDetail = "";
            },
          },
          { type: "select", label: "风险等级", prop: "riskLevel" },
          { type: "textarea", label: "风险描述", prop: "holeDetail" },
          {
            type: "operation",
            style: { "text-align": "right" },
            children: [
              {
                label: "取 消",
                click: () => {
                  this.indexDiaShow = false;
                },
              },
              {
                label: "确 认",
                type: "primary",
                click: () => {
                  if (this.$refs.monitoringIndex.submitForm()) {
                    console.log(this.selectRiskName);
                    // console.log("执行");
                    saveRiskItemApi({
                      monitorId: this.query.id,
                      reportItem: this.selectRiskName.code,
                      domain: this.contentData.domain,
                      pocRiskLevel: this.newIndex.ruleForm.riskLevel,
                      remark: this.newIndex.ruleForm.holeDetail,
                    }).then((res) => {
                      this.indexDiaShow = false;
                      let state = this.message.state(res);
                      if (!state) return;
                      this.getRiskList();
                    });
                  }
                },
              },
            ],
          },
        ],
      },
      ruleForm: {
        remark: "",
      },
      rules: {
        remark: [{ required: true, message: config.input, trigger: "blur" }],
      },
      formData: [
        { type: "textarea", label: "备注", prop: "remark" },
        {
          type: "operation",
          style: { "text-align": "right" },
          children: [
            {
              label: "取 消",
              click: () => {
                this.errDiaShow = false;
              },
            },
            {
              label: "确 认",
              type: "primary",

              click: () => {
                if (this.$refs.errReport.submitForm()) {
                  this.errReportConfirm();
                }
              },
            },
          ],
        },
      ],
      //监控指标tab界面数据
      //url列表
      urlTable: {
        cols: [
          { label: "URL", prop: "url" },
          { label: "说明", prop: "remark" },
          { label: "负责人", prop: "urlLeader" },
          { label: "发生时间", prop: "createTime" },
          {
            label: "操作",
            prop: "operation",
            width: 100,
            children: [
              {
                labelFunc: ({ row, column, $index }) => {
                  //加白和不加白的显示 通过策略类型判断 如果是url策略展示 系统策略就不展示
                  if (row.strategyType == 1 && row.white == 1) {
                    return "取消加白";
                  } else if (row.strategyType == 1) {
                    return "加白";
                  } else {
                    return "-";
                  }
                },
                click: ({ row, column, $index }) => {
                  this.selectUrlRow = row;
                  if (row.strategyType == 1 && row.white == 1) {
                    this.addWhiteHandler("cancel", "subsystem_monitor");
                  } else if (row.strategyType == 1) {
                    this.addWhiteHandler("add", "subsystem_monitor");
                  }
                },
              },
            ],
          },
        ],
        rows: [],
      },
      evalResult: {
        cols: [
          { label: "指标ID", prop: "templateItemId" },
          { label: "指标名称", prop: "templateItemName" },
          {
            label: "指标来源",
            prop: "scene",
            formatter: (row, column, cellValue, index) => {
              let t = "";
              if (Array.isArray(cellValue)) {
                cellValue.forEach((e) => {
                  t += this.utils.getDicLabel(101003, e) + ",";
                });
                return t.slice(0, -1);
              }
              return t;
            },
          },
          { label: "指标要求", prop: "reportItemContent" },
          {
            label: "是否必须",
            prop: "required",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel(101004, cellValue);
            },
          },
          {
            label: "是否自动化",
            prop: "auto",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel(101004, cellValue);
            },
          },
          {
            label: "风险等级",
            prop: "pocRiskLevel",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("level", cellValue);
            },
          },
          {
            label: "审计结果",
            prop: "status",
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("status", cellValue);
            },
          },
          { label: "现状描述", prop: "remark" },
          {
            label: "操作",
            prop: "operation",
            width: 100,
            fixed: "right",
            children: [
              {
                label: "URL列表",
                click: ({ row, column, $index }) => {
                  this.urlDiaShow = true;
                  this.selectIndexRow = row;
                  this.getRiskUrls();
                },
              },
            ],
          },
        ],
        rows: [{ templateItemId: 1, scene: 222 }],
      },
    };
  },
  computed: {},
  mounted() {
    this.codeSessionSign = getCodeSession();
    this.query = this.$route.query;
    this.getAssetsDetail(); //资产信息
    this.getMonitorDetail(); //监控信息
    this.getRiskList();
    this.getMonitorGetItems();
    this.getListAllTinyRisk();
  },
  methods: {
    //url列表数据
    getRiskUrls() {
      riskUrlsApi({ dateType: "subsystem_monitor", itemId: this.selectIndexRow.monitorItemId }).then((res) => {
        this.urlTable.rows = res.data;
        let paramType = res.data[0].paramType || "URL";
        this.urlTable.cols[0].label = paramType;
      });
    },
    //选中风险名称
    getChangeRiskData() {
      let riskItem = this.allRiskData.filter((item) => {
        return item.id === this.newIndex.ruleForm.holeName;
      });
      if (riskItem && riskItem.length > 0) {
        this.selectRiskName = riskItem[0];
        this.newIndex.ruleForm.riskLevel = riskItem[0].riskLevel + "";
        this.newIndex.ruleForm.holeDetail = riskItem[0].holeDetail;
      }
    },
    getListAllTinyRisk() {
      listAllTinyRiskApi().then((res) => {
        console.log(res);
        this.allRiskData = res.data;
        this.newIndex.optionData.holeName = res.data;
      });
    },
    //监控信息
    getMonitorDetail() {
      subsystemMonitorDetailApi({ assetCode: this.query.domain, assetType: this.query.assetType }).then((res) => {
        this.contentData = { ...this.contentData, ...res.data };
      });
    },
    //资产信息
    getAssetsDetail() {
      let loading = this.openLoading();
      assetSubsystemDetailApi({ id: this.query.assetId }).then((res) => {
        loading.close();
        this.contentData = { ...this.contentData, ...res.data };
      });
    },
    //监控指标
    getMonitorGetItems() {
      subsystemMonitorGetItemsApi({ monitorId: this.query.id }).then((res) => {
        this.evalResult.rows = res.data;
      });
    },
    /**
     * @函数功能:获取风险列表数据
     * @参数输入:
     * @函数返回:
     */
    getRiskList() {
      this.riskTable.loading = true;
      riskListApi({
        assetId: this.query.assetId,
        dateType: ["subsystem_monitor"],
        pageNum: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        this.riskTable.loading = false;
        this.riskTable.rows = res.data;
        this.totalSize = res.count;
      });
    },
    /**
     * @函数功能:同步漏洞平台 弹框的确认按钮
     * @参数输入:
     * @函数返回:
     */
    asyncHoleConfirm() {
      riskSocApi({ riskIds: [this.selectRisk.id], dateType: "subsystem_monitor" }).then((res) => {
        this.holeDiaShow = false;
        this.message.success({ message: res.msg });
        this.getRiskList();
      });
    },
    //误报
    errReportConfirm() {
      riskMisreportApi({ ids: [this.selectRisk.id], status: "12", remark: this.ruleForm.remark }).then((res) => {
        this.errDiaShow = false;
        this.message.success({ message: res.msg });
        this.getRiskList();
      });
    },
    //添加监控指标
    // saveRiskItem() {
    //   let { riskName, level, remark } = this.newIndex.ruleForm;
    //   saveRiskItemApi({
    //     reportItem: "", //在获取风险名称的时候，拿到的
    //     domain: riskName,
    //     itemLevel: level,
    //     remark: remark,
    //   }).then((res) => {
    //     this.indexDiaShow = false;
    //     this.message.success({ message: res.msg });
    //     this.getRiskList();
    //   });
    // },
    //添加监控指标 点击
    addMonitorIndex() {
      this.newIndex.ruleForm.holeName = "";
      this.newIndex.ruleForm.riskLevel = "";
      this.newIndex.ruleForm.holeDetail = "";
      this.indexDiaShow = true;
    },
    //发起监控扫描 按钮点击
    monitorScan() {
      let loading = this.openLoading();
      subsystemMonitorStartApi({ assetId: this.query.assetId }).then((res) => {
        loading.close();
        this.message.success({ message: res.msg });
      });
    },
    sizeChange(val) {
      this.pageSize = val;
      this.getRiskList();
    },
    currentChange(val) {
      this.page = val;
      this.getRiskList();
    },
  },
  watch: {},
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
</style>
